package com.ptu.ws;

import com.ptu.entity.ChatMessage;
import com.ptu.ws.service.ChatMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/chat")
public class ChatController {

    @Autowired
    private ChatMessageService chatMessageService;

    @GetMapping("/history")
    public ResponseEntity<?> getHistoryMessages(
            @RequestParam(required = false) String sender,
            @RequestParam(required = false) String receiver) {

        System.out.println("获取历史消息");
        
        // 参数验证
        if (!StringUtils.hasText(sender) || !StringUtils.hasText(receiver)) {
            return ResponseEntity.badRequest()
                .body(new ErrorResponse("发送者和接收者不能为空"));
        }

        try {
            List<ChatMessage> messages = chatMessageService.getMessagesBetweenUsers(sender, receiver, 50);
            return ResponseEntity.ok(messages);
        } catch (Exception e) {
            return ResponseEntity.internalServerError()
                .body(new ErrorResponse("获取历史消息失败: " + e.getMessage()));
        }
    }

    // 错误响应类
    private static class ErrorResponse {
        private final String message;
        private final long timestamp;

        public ErrorResponse(String message) {
            this.message = message;
            this.timestamp = System.currentTimeMillis();
        }

        public String getMessage() {
            return message;
        }

        public long getTimestamp() {
            return timestamp;
        }
    }
} 